import { MutableRefObject, RefCallback, RefObject, useCallback } from "react";
import useLatestRef from "./useLatestRef";

export default function useMergeRefs<T = null>(
  ...refs: (null | undefined | MutableRefObject<T> | RefCallback<T>)[]
) {
  const _refs = useLatestRef(refs);
  const mergedRefsFn = useCallback((instance: T) => {
    _refs.current.forEach((ref) => {
      if (!ref) {
        return;
      }
      if (typeof ref === "function") {
        ref(instance);
      } else if (typeof ref === "object") {
        ref.current = instance;
      }
    });
  }, []); // eslint-disable-line

  return mergedRefsFn;
}
